<template>
  <div v-if="!showComponentName" class="my-knowledge">
    <div class="add_btns_box">
      <div class="box_left">
        <div class="title">我的知识库</div>
      </div>
      <div class="box_right">
        <Space>
          <Input v-model="searchValue" placeholder="知识库名称" @on-blur="getPageData(true)" />
          <Button type="primary" @click="editKnowledge">新建</Button>
        </Space>
      </div>
    </div>

    <div class="list-box" v-loading="loading">
      <div ref="cardContentRef" class="card-content">
        <div v-for="item in pageData" :key="item.id" class="row-car" @click="toTablePage(item)">
          <div class="title">
            <Icon type="logo-octocat" size="22" />
            <Tooltip transfer theme="light" :content="item.name" placement="top">
              <p class="name">{{ item.name }}</p>
            </Tooltip>
          </div>

          <div class="car-type">
            <Button icon="md-book" type="text">{{ item.kbdoctype }}</Button>
          </div>

          <p class="desc">{{ item.description || '这个知识库还没有介绍~' }}</p>

          <div class="btns">
            <Button icon="ios-easel" type="text">{{ item.orgi }}</Button>
            <Button icon="md-lock" type="text">私有</Button>

            <Button class="gpt-type-btn" icon="md-boat" type="text">gpt-tye</Button>
            <Button
              class="delete-btn"
              icon="md-trash"
              type="text"
              @click.stop="handleDelete(item.id)"
              >删除</Button
            >
          </div>
        </div>
      </div>

      <!-- <div v-if="nextLoading" class="next-loging">
        <Icon type="logo-octocat" size="22" />
      </div> -->

      <div v-if="!pageData.length && !loading" class="no-thing">暂无数据~</div>
    </div>

    <Page
      v-model="pageIndex"
      :page-size="pageSize"
      :total="total"
      show-elevator
      show-total
      @on-change="getPageData()"
    />
  </div>

  <component
    v-else
    :is="showComponentName"
    @back="cancelShowComponent"
    @update="getPageData(true)"
  />
</template>

<script setup>
import { ref, onMounted, inject, markRaw, getCurrentInstance, provide } from 'vue'

import { myKnowledge } from '@/api/modules/knowledgeBase'
import { agentList } from '@/api/modules/agent'
import { Message } from 'view-ui-plus'
import CreateKnowledge from './CreateKnowledge/index.vue'
import KnowledgeTable from './KnowledgeTable/index.vue'

const changeArrange = inject('changeArrange')
const { proxy } = getCurrentInstance()
const searchValue = ref('')

const showComponentName = ref(null)
const typeId = inject('typeId')
const pageData = ref([])
const loading = ref(false)
const nextLoading = ref(true)
const pageIndex = ref(1)
const pageSize = 30
const total = ref(0)

const getPageData = (reset) => {
  loading.value = true
  if (reset) {
    pageIndex.value = 1
  }

  return myKnowledge
    .catePage({
      query: {
        p: pageIndex.value,
        ps: pageSize
      },
      data: {
        aitype: 'kb',
        kbtype: typeId.value,
        name: searchValue.value
      }
    })
    .then(({ data }) => {
      const list = data?.topicList || []
      // if(reset) {
      pageData.value = list
      // }else{
      //   pageData.value.push(...list)
      // }

      total.value = data.totalElements
    })
    .finally(() => {
      loading.value = false
    })
}

const handleDelete = (id) => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否删除该数据?!</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await myKnowledge.cateDelete({
        data: {
          id
        }
      })

      Message.success('删除成功')

      getPageData()
    }
  })
}

const editKnowledge = () => {
  showComponentName.value = markRaw(CreateKnowledge)

  changeArrange()
}

const selectId = ref(null)
const toTablePage = (data) => {
  selectId.value = data.id
  showComponentName.value = markRaw(KnowledgeTable)
  changeArrange()
}

const cancelShowComponent = () => {
  showComponentName.value = null

  changeArrange(true)
}

provide('getTypeId', () => selectId.value)
provide('homeUpdate', getPageData)

const cardContentRef = ref(null)
const hasMore = ref(true)
const initInter = () => {
  // 创建一个观察者元素，放在内容的底部
  const loadingElement = document.createElement('div')
  loadingElement.className = 'loading-indicator'
  loadingElement.style.height = '1px'
  loadingElement.style.width = '100%'
  cardContentRef.value.appendChild(loadingElement)

  const intersectionObserver = new IntersectionObserver(
    async (entries) => {
      // 当观察元素进入视口
      if (entries[0].isIntersecting && pageData.value.length < total.value && !loading.value) {
        console.log('Reached bottom, loading more items')
        pageIndex.value += 1
        nextLoading.value = true
        try {
          await getPageData()
        } finally {
          nextLoading.value = false
        }
      }
    },
    {
      root: null, // 使用视口作为根元素
      rootMargin: '0px', // 根元素的边界偏移量
      threshold: 0.1 // 当目标元素有10%进入视口时触发
    }
  )

  // 开始监听
  intersectionObserver.observe(loadingElement)

  // 保存观察者实例以便在组件卸载时清理
  return intersectionObserver
}
onMounted(() => {
  getPageData()
  // initInter()
})

defineExpose({
  getPageData
})
</script>

<style scoped lang="scss">
.my-knowledge {
  height: 100%;
  .list-box {
    position: relative;
    height: calc(100vh - 200px);
    overflow-y: auto;
    padding-right: 10px;
    .card-content {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      // justify-content: space-between;
      grid-gap: 8px;
      padding: 12px 0;
      // height: 100%;

      .row-car {
        background-color: #fff;
        display: inline-flex;
        flex-direction: column;
        height: 100%;
        cursor: pointer;
        border: 1px solid #dfe2e9;
        border-radius: 8px;
        box-shadow: 2px 3px 19px 1px #dfe2e9;
        min-height: 150px;
        user-select: none;
        padding: 12px;
        position: relative;
        // width: 265px;
        // margin: 0 20px 20px 0;
        // min-width: 240px;
        &:hover {
          border-color: #4a8ae9;
          .btns {
            .gpt-type-btn {
              display: none;
            }
            .delete-btn {
              display: block;
            }
          }
        }
        .title {
          font-size: 16px;
          display: flex;
          align-items: center;
          .ivu-tooltip {
            line-height: 1;
            margin-left: 4px;
          }
          .name {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            max-width: 140px;
          }
        }
        .car-type {
          position: absolute;
          top: 12px;
          right: 0;
          background-color: #f4f4f7;
          border-radius: 6px 0 0 6px;
          padding-left: 4px;
        }
        .delete-icon {
          position: absolute;
          top: 4px;
          right: 4px;
        }
        .desc {
          margin-top: 16px;
          color: #667085;
          overflow-y: auto;
        }
        .btns {
          display: flex;
          margin-top: auto;
          .delete-btn {
            display: none;
            margin-left: auto;
            color: #ff0000;
          }
          .gpt-type-btn {
            margin-left: auto;
          }
        }
        .ivu-btn {
          padding: 0;
          height: unset;
          &:first-child {
            margin-right: 8px;
          }

          &:last-child {
            margin-left: auto;
          }
        }
      }
    }

    .no-thing {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      // margin: auto;
      color: #999;
      font-size: 16px;
    }
  }
}
</style>
